// Console fix
if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() {} }; 

// Vars
var tutorial_match_end, miniGameId;

// *** Language ***
//"Normal","Meget defensiv","Defensiv","Lidt defensiv","Lidt offensiv","Offensiv","Meget offensiv"
var mentality_language_ar = [pagecontent[20],pagecontent[21],pagecontent[22],pagecontent[23],pagecontent[20],pagecontent[24],pagecontent[25],pagecontent[26]];
var match_type_language_ar = {"international_cup":pagecontent[27],"league":global_content[484],"friendly":global_content[486],"friendly_league":global_content[487],"cup":global_content[485]};
//"Outstanding","Superb","Excellent","Good","Decent","Poor","Wretched","Despicable"
var pitch_condition_language_ar = [pagecontent[28],pagecontent[29],pagecontent[30],pagecontent[31],pagecontent[32],pagecontent[33],pagecontent[34],pagecontent[35]];
//"Balanced", "Balanced", "Direct", "Wings", "Shortpassing", "Long Balls", "Through Balls"
var style_language_ar = [pagecontent[36],pagecontent[36],pagecontent[37],pagecontent[38],pagecontent[39],pagecontent[40],pagecontent[41]];
var wdl_language_ar = {"w":pagecontent[42],"d":pagecontent[43],"l":pagecontent[44]};

var language = {
	"tooltip_play_button":pagecontent[5],
	"tooltip_speed_normal_button":pagecontent[6],
	"tooltip_speed_fast_button":pagecontent[7],
	"tooltip_events_all_button":pagecontent[8],
	"tooltip_events_key_button":pagecontent[9],
	"tooltip_skip_button":pagecontent[10],
	"tba":pagecontent[11],
	"tbah":pagecontent[12],
	"possession":pagecontent[13],
	"shots":pagecontent[14],
	"shots_on_target":pagecontent[15],
	"set_pieces":pagecontent[16],
	"penalties":pagecontent[17],
	"ycards":pagecontent[18],
	"rcards":pagecontent[19],
	"waiting_kickoff":pagecontent[74],
	"waiting_weather":pagecontent[75],
	"prematch_info":pagecontent[76]
};
// *** Language end ***

// Presets and scope
var live = false;
var qm_mode = false;
var nt_mode = false;

var end_of_game = false;
var half_time = false;
var event_list_ar = new Array();
var lineup_both = new Object();
var last_events_and_stats_update;
var match_data = null;

var match_seconds = 0;
var match_time_mode = "relive";	// "relive"/"live"/"prematch"/"forfeit"
var match_half_time = false;	// false/int
var match_last_regular_min = 95;

var match_next_minute = 0;	// Next match minute, saved between severity changes
var match_last_min = -1;	// The last minute seen
var match_last_stats_min = -1;	// The last minute with stats generated


var flash_status =  {
	"loaded_main":false,
	"loaded_refblow":false,
	"loaded_first_sequence":false,
	"report_started":false,
	"playback_mode":"play",
	"enabled":true
};

var flash_finished_loaded_minutes_ar = [];	// Array of minutes finished loaded by the flash
var flash_start_loaded_minutes_ar = [];		// Array of minutes started loaded by the flash
var flash_played_minutes_ar = [];			// The last minute played by the flash
var flash_playing_clip = false;				// Flash currently playing a clip
var flash_player_info = {};


var skip_to_minute = 0;

// Settings
var settings = {
	"severity":1 	// 0 all, 1 important only
};

// Team colors, w/ default
var team_colors = {
	"home":{"0":"ff0000","1":"ffffff","2":"ff0000","rgb":"255,0,0"},
	"away":{"0":"0000ff","1":"000000","2":"0000ff","rgb":"0,0,255"}
};

// Tabs
var tab_active = null;
var tab_valid_ar = null;
	
// Elements
var element_stats, element_score, element_home_player_list, element_away_player_list, element_field, element_venue, element_live_score, element_live_standing;

// Data
var data_match_stats = {
	// 		[home,away]
	"score":[0,0],
	"shots":[0,0],
	"shots_on_target":[0,0],
	"set_pieces":[0,0],
	"penalty":[0,0],
	"yellow":[0,0],
	"red":[0,0]
};


// TABS
var tab_data = {
	"stats":{
		"header":pagecontent[86],
		"content":"<div class='half text_center'></div>"
	},
	
	"field":{
		"header":pagecontent[87],
		"content":"<div class='quarter home'></div><div class='half'></div><div class='quarter away'></div>"
	},
	
	"league":{
		"header":pagecontent[91],
		"content":"<div class='tcenter'><img src='/pics/small_loading.gif' /></div>"
	},
	
	"events":{
		"header":pagecontent[47],
		"content":"<div class='half'><ul class='event_list clean underlined large_padding'></ul></div><div class='half'><ul class='report_list clean underlined text_left'></ul></div>"
	},
	
	"head_to_head":{
		"header":pagecontent[89],
		"content":"<img src='/pics/small_loading.gif' />"
	},
	
	"stadium":{
		"header":pagecontent[88],
		"content":"<div class='half'></div><div class='half'></div>"
	},
	
	"chat":{
		"header":pagecontent[90],
		"content":"<div id='disable_chat_btn'></div><div id='chatroom'></div><input id='chattext'></input>"
	}
};

var tabs_to_show_ar = {
	"other": ["field","events","stadium","head_to_head","chat"],
	"league":	["field","league","events","stadium","head_to_head","chat"],
	"prematch":	["field","stadium","head_to_head","chat"],
	"friendly":	["field","events","stadium","head_to_head","chat"]
}


function get_tab_data(entry) {
	if (tab_data[entry]) return tab_data[entry];
	console.log("Tab error!");
	return false;
}






var head_to_head_loaded = false;
function load_head_to_head() {
	if (head_to_head_loaded) return false;
	$.ajax({
		url: "/ajax/match_h2h.ajax.php",
		dataType: 'json',
		data: {
			"home_team":home_team["id"],
			"away_team":away_team["id"],
			"date":match_info.venue.kickoff,
			miniGameId: miniGameId,
		},
		success: load_head_to_head_success,
		error: load_head_to_head_error
	});
}

function load_head_to_head_success(data) {
	head_to_head_loaded = true;
	$("[tab=head_to_head]").empty().append(
		template_head_to_head_overview(data["matches"]),
		template_head_to_head_list(data["matches"])
	);
}

function load_head_to_head_error(data) {};





var league_loaded = false;
function load_live_data() {

	if (league_loaded) return false;
	
	$.ajax({
		url: "/ajax/match_leaguescores.ajax.php",
		dataType: 'json',
		data: {
			"id":match_id,
			"country":home_team["country"],
			"division":home_team["division"],
			"group":home_team["group"],
			"time":venue["kickoff"],
			miniGameId: miniGameId,
		},
		success: load_live_data_success,
		error: load_live_data_error
	});

};


function load_live_data_success(data) {
	league_loaded = true;
	live = new Object();
	live["last_update"] = -1;
	
	// Goals
	live["goals"] = data["livescores"]["live"];
	
	// Matches
	live["matches"] = new Object();
	for (var i in data["livescores"]["match"]) {
		var row = data["livescores"]["match"][i];
		live["matches"][i] = {
			"match_id":i,
			"scorers":[],
			"score":[0,0],
			"away":{
				"id":row["away"]["id"],
				"name":row["away"]["name"]
			},
			"home":{
				"id":row["home"]["id"],
				"name":row["home"]["name"]
			}
		};
	}
	
	// League
	live["league"] = new Object();
	for (var i in data["league"]) {
		var id = data["league"][i]["club_id"];
		live["league"][id] = {
			"bonus":1,
			"bonus_goals":0,
			"name":data["league"][i]["name"],
			"id":data["league"][i]["club_id"],
			"points":data["league"][i]["points"],
			"goals":data["league"][i]["goals"],
			"goals_difference":data["league"][i]["goals_difference"],
			"goals_against":data["league"][i]["goals_against"],
			"old_standing":i
		};
	}
	
	
	element_live_score = template_live_scores(live["matches"]);
	element_live_standing = template_live_standings(live["league"]);

	// Add elements to dom
	$("[tab=league]").empty().append(
		element_live_score,
		element_live_standing
	);
	
	update_live_elements();
	
};
function load_live_data_error(data) {};



// Live league functions
function add_live_goals(goals, time) {

	for (var i in goals) {
	
		var goal = goals[i];
		
		// Live scores
		var match = live["matches"][goal["id"]];
		
		match["score"] = goal["score"];
		
		goal["scorer"]["score"] = goal["score"];		
		goal["scorer"]["time"] = time;
		
		match["scorers"].push(goal["scorer"]);
		
		
		// Live standings
		var home_team = live["league"][match["home"]["id"]];
		var away_team = live["league"][match["away"]["id"]];
		
		home_team["bonus_goals"] = parseInt(goal["score"][0])-parseInt(goal["score"][1]);
		away_team["bonus_goals"] = parseInt(goal["score"][1])-parseInt(goal["score"][0]);

		if (goal["score"][0] > goal["score"][1]) {
			// home is winning
			home_team["bonus"] = 3;
			away_team["bonus"] = 0;

		} else if (goal["score"][0] < goal["score"][1]) {
			// away is winning
			home_team["bonus"] = 0;
			away_team["bonus"] = 3;

		} else if (goal["score"][0] == goal["score"][1]) {
			// draw
			home_team["bonus"] = 1;
			away_team["bonus"] = 1;

		}
		
	}
}

var site_prefix = "tm_";

// Load match
function load_match_success(data) {

	// Setup data
	match_data = data;
	
	home_team = match_data["club"]["home"];
	away_team = match_data["club"]["away"];

	match_info = (match_data["match_data"] != undefined) ? match_data["match_data"] : false;
	lineup = (match_data["lineup"] != undefined) ? match_data["lineup"] : false;
	report = (match_data["report"] != undefined) ? match_data["report"] : false;

	// Set end of game
	match_last_regular_min = parseInt(match_info["regular_last_min"]);
	end_game = (match_data["match_data"]["last_min"]) ? parseInt(match_data["match_data"]["last_min"]) : parseInt(match_last_regular_min);

	/*
	if (data["livescores"] != undefined) {
		live["scores"] = (data["livescores"]["live"] != undefined) ? data["livescores"]["live"] : false;
	}
	*/

	if (match_info) {
	
		// Add start mentality and style
		if (match_info["attacking_style"] && match_info["mentality"]) {
			match_info["start_attacking_style"] = {
				"home":match_info["attacking_style"]["home"],
				"away":match_info["attacking_style"]["away"]
			};
			match_info["start_mentality"] = {
				"home":match_info["mentality"]["home"],
				"away":match_info["mentality"]["away"]
			};
		}

		if (match_info["venue"] != undefined) {
			venue = match_info["venue"];
			preload("/pics/matchviewer/venue_"+venue["picture"]+".png");
			preload(get_weather_url(venue["weather"]));
			
			if (venue["matchtype"] == "ntc" || venue["matchtype"] == "ntg" || venue["matchtype"] == "ntq" || venue["matchtype"] == "ntf") {
				nt_mode = true;
			}
			
		} else {
			venue = false;
		}
		
		qm_mode = match_info["qm"] || false;

	}
	
	
	
	// Override
	if (SESSION["id"] == 9067) {
		//match_info["live_min"] = 44;
		//match_seconds = 80*60;
		//skip_to_minute = 9;
	}
	
	// Default tabs
	if (venue['matchtype']=="l") tab_valid_ar = tabs_to_show_ar["league"];
	else tab_valid_ar = tabs_to_show_ar["other"];
	
	// Set mode
	
			
	if (match_info["forfeit"] != undefined) {
		// Game is forfeited
		match_time_mode = "forfeit";
		if (match_data["match_data"]["forfeit"]["side"] == "home") {
			score = [0,3];
		} else if (match_data["match_data"]["forfeit"]["side"] == "away") {
			score = [3,0];
		} else {
			score = [0,0];
		}
		
	} else if (match_info["live_min"] != undefined) {
	
		// Mode is LIVE
		if (parseInt(match_info["live_min"]) >= 0) {
	
			match_time_mode = "live";
			
			// Set time and half time
			var live_min = parseInt(match_info["live_min"]);
			
			if (live_min < 45) {
				skip_to_minute = live_min;
			} else if (live_min < 60) {
				skip_to_minute = 45;
				match_half_time = (live_min-45)*60;
			} else {
				skip_to_minute = live_min-15;
				match_half_time = true;
			}
			settings["severity"] = 0;
			
			
			
		
		// Mode is PREMATCH
		} else {
			match_time_mode = "prematch";
			
			// Set tabs
			tab_valid_ar = tabs_to_show_ar["prematch"];
			
			countdown = Math.abs(parseInt(match_info["live_min"]))*60;
			$("#tabs .league, #tabs .events").hide();
		}
	
	} else {
	
		match_time_mode = "relive";
		
		// Set tabs
		if (qm_mode || venue["matchtype"] == "fl") {
			tab_valid_ar = tabs_to_show_ar["friendly"];
		}
		
	}

	
	

	// Setup team data
	// Page title
	if (home_team["club_name"] && away_team["club_name"]) {
		$(document).attr("title", "Match * "+home_team["club_name"]+" vs. "+away_team["club_name"]+" * TrophyManager.com");
	}
	
	// Team colors
	function get_nonsimilar_color(color) {
		var color_ar = ["cc0000","00cc00","0000cc","cccccc","000000"];
		for (var i in color_ar) {
			if (!test_colors_are_close(color, color_ar[i])) return color_ar[i];
		}
		return "ff9900";
	}
		
	// Fix colors
	function fix_colors(str) {
		if(str) {
			return (str.length==6) ? str : "000000";
		}
		return "000000";
	}
	
	match_data["club"]["home"]["colors"]["club_color1"] = fix_colors(match_data["club"]["home"]["colors"]["club_color1"]);
	match_data["club"]["home"]["colors"]["club_color2"] = fix_colors(match_data["club"]["home"]["colors"]["club_color2"]);
	match_data["club"]["home"]["colors"]["club_color3"] = fix_colors(match_data["club"]["home"]["colors"]["club_color3"]);
	
	match_data["club"]["away"]["colors"]["club_color1"] = fix_colors(match_data["club"]["away"]["colors"]["club_color1"]);
	match_data["club"]["away"]["colors"]["club_color2"] = fix_colors(match_data["club"]["away"]["colors"]["club_color2"]);
	match_data["club"]["away"]["colors"]["club_color3"] = fix_colors(match_data["club"]["away"]["colors"]["club_color3"]);
	match_data["club"]["away"]["colors"]["club_color4"] = fix_colors(match_data["club"]["away"]["colors"]["club_color4"]);
	match_data["club"]["away"]["colors"]["club_color5"] = fix_colors(match_data["club"]["away"]["colors"]["club_color5"]);
	match_data["club"]["away"]["colors"]["club_color6"] = fix_colors(match_data["club"]["away"]["colors"]["club_color6"]);
	
	
	// Add team colors
	// Home
	team_colors["home"][0] = match_data["club"]["home"]["colors"]["club_color1"];
	team_colors["home"][1] = match_data["club"]["home"]["colors"]["club_color2"];
	team_colors["home"][2] = match_data["club"]["home"]["colors"]["club_color3"];
	team_colors["home"]["rgb"] = get_semi_desatuated_color_rgb(match_data["club"]["home"]["colors"]["club_color1"]);
	
	// Away
	if (!test_colors_are_close(match_data["club"]["home"]["colors"]["club_color1"], match_data["club"]["away"]["colors"]["club_color4"])) {
		// Non-similar shirts: add away kit
		team_colors["away"][0] = match_data["club"]["away"]["colors"]["club_color4"];
		team_colors["away"][1] = match_data["club"]["away"]["colors"]["club_color5"];
		team_colors["away"][2] = match_data["club"]["away"]["colors"]["club_color6"];
		team_colors["away"]["rgb"] = get_semi_desatuated_color_rgb(match_data["club"]["away"]["colors"]["club_color4"]);
		
	} else if (!test_colors_are_close(match_data["club"]["home"]["colors"]["club_color1"], match_data["club"]["away"]["colors"]["club_color1"])) {
		// Similar shirts: add home kit
		team_colors["away"][0] = match_data["club"]["away"]["colors"]["club_color1"];
		team_colors["away"][1] = match_data["club"]["away"]["colors"]["club_color2"];
		team_colors["away"][2] = match_data["club"]["away"]["colors"]["club_color3"];
		team_colors["away"]["rgb"] = get_semi_desatuated_color_rgb(match_data["club"]["away"]["colors"]["club_color1"]);
		
	} else {
		// Still similar shirts: add auto generated kit
		var generated_color = get_nonsimilar_color(match_data["club"]["home"]["colors"]["club_color1"]);
		team_colors["away"][0] = generated_color;
		team_colors["away"][1] = match_data["club"]["away"]["colors"]["club_color5"];
		team_colors["away"][2] = match_data["club"]["away"]["colors"]["club_color6"];
		team_colors["away"]["rgb"] = get_semi_desatuated_color_rgb(generated_color);
		
	}


	// Fix and juggle the data
	for (var i in lineup["home"]) {
		lineup["home"][i]["match_stats"] = [];
		lineup["home"][i]["start_position"] = lineup["home"][i]["position"];
		// html entities fix
		lineup["home"][i]["name"] = $("<div>").html(lineup["home"][i]["name"]).html();
		lineup_both[i] = lineup["home"][i];

		
		// Flash appearance
		//Data  Order : Hair Type , Body Color,Shirt Color,Pant Color,Hair Color,Socks Color,Name,Name Color
		// Name fix
		var name_fix = lineup["home"][i]["name"].split(". ");
		name_fix = name_fix.pop();
		name_fix = lineup["home"][i]["no"]+"."+name_fix;
		var appearance = [
			lineup["home"][i]["looks"]["hair"], //hair_type
			"0x"+lineup["home"][i]["looks"]["skin_color"], //skin_color
			"0x"+team_colors["home"][0], //shirt_color
			"0x"+team_colors["home"][1], //pants_color
			"0x"+lineup["home"][i]["looks"]["hair_color"], //hair_color
			"0x"+team_colors["home"][2], //socks_color
			//lineup["home"][i]["no"]+" "+lineup["home"][i]["name"], //name_text
			name_fix, //name_text
			"0xFFFFFF" //text_color
		];
		// Override for GK shirts
		if (lineup["home"][i]["position"] == "gk") {
			appearance[2] = "0xf6b10b"; //shirt_color - orangeish
			appearance[3] = "0x000000"; //pants_color
			appearance[5] = "0x000000"; //socks_color
		}
		flash_player_info[i] = appearance;
	}
	for (var i in lineup["away"]) {
		lineup["away"][i]["match_stats"] = new Array();
		lineup["away"][i]["start_position"] = lineup["away"][i]["position"];
		// html entities fix
		lineup["away"][i]["name"] = $("<div>").html(lineup["away"][i]["name"]).html();
		lineup_both[i] = lineup["away"][i];
		
		// Flash appearance
		// Name fix
		var name_fix = lineup["away"][i]["name"].split(". ");
		name_fix = name_fix.pop();
		name_fix = lineup["away"][i]["no"]+"."+name_fix;
		var appearance = [
			lineup["away"][i]["looks"]["hair"], //hair_type
			"0x"+lineup["away"][i]["looks"]["skin_color"], //skin_color
			"0x"+team_colors["away"][0], //shirt_color
			"0x"+team_colors["away"][1], //pants_color
			"0x"+lineup["away"][i]["looks"]["hair_color"], //hair_color
			"0x"+team_colors["away"][2], //socks_color
			//lineup["away"][i]["no"]+" "+lineup["away"][i]["name"], //name_text
			name_fix, //name_text
			"0xFFFFFF" //text_color
		];
		// Override for GK shirts
		if (lineup["away"][i]["position"] == "gk") {
			appearance[2] = "0x94e941"; //shirt_color - greenish
			appearance[3] = "0x000000"; //pants_color
			appearance[5] = "0x000000"; //socks_color
		}
		flash_player_info[i] = appearance;
	}

	// Fade out loading
	$(".mv_controls span").fadeOut(300);
	
	setTimeout(pop_top_element, 400);
		
	if (match_time_mode == "forfeit") {
		// Forfeit game
		$(".mv_bottom").remove();
		var ff_text = match_data.match_data.forfeit.text[0][0];
		$(".clock").html("Forfeit <img src='/pics/icons/question_mark_small.png'>").tooltip(ff_text);
		$(".score").text(score[0]+" - "+score[1]);
		// tutorial function
		if (typeof tutorial_match_end == "function") tutorial_match_end();

	} else {
		setTimeout(pop_element_with_data, 400);
	}
}

function load_match_error(data) {
	$(".mv_controls span").fadeOut(300);
	$(".mv_controls").empty().append(
		$("<span>").text(pagecontent[73]).addClass("text")
	);

}

function load_match() {

	$.ajax({
		url: "/ajax/match.ajax.php",
		dataType: 'json',
		data: {
			"id":match_id,
			miniGameId: miniGameId,
		},
		success: load_match_success,
		error: load_match_error,
	});

}

/*
function pop_action_force(sec) {

	var time = time_split(sec);

	var last_action = null;
	var last_action_min = 0;

	for (var i=time.m-1; i>=0; i--) {
		if (report[i]) {
			last_action_min = i;
			last_action = report[i];
			break;
		}
	}
	if (last_action != null) {
		var tmp_action_queue = [];

		for (var i in last_action) {

			tmp_action_queue = get_action_array(last_action[i], get_display_time(last_action_min).formatted_m);

			for (var i in tmp_action_queue) {
				action_run(tmp_action_queue[i], true);
			}

		}
	}

}
*/

function pop_top_element() {
	
	// Setup page with team data
	// Add team colors
	$(".home_color").animate({"background-color":"rgb("+team_colors["home"]["rgb"]+")"}, 1000);
	$(".away_color").animate({"background-color":"rgb("+team_colors["away"]["rgb"]+")"}, 1000);
	
	
	// Top logos
	if (nt_mode) {
		$(".home_logo").append(
			$("<img>").css({height:"80px", width:"80px"}).attr("src", "/pics/nt_logos/80px/"+home_team["country"]+".png").fadeIn(1000)
		);
		$(".away_logo").append(
			$("<img>").css({height:"80px", width:"80px"}).attr("src", "/pics/nt_logos/80px/"+away_team["country"]+".png").fadeIn(1000)
		);
	} else {
	
		//var home_logo = ;
		$(".top_team_bars .home_logo").append(
			$("<img class='logo' src='"+home_team["logo"]+"' />").attr("club_link", home_team["id"]).fadeIn(1000)
		);
		$(".top_team_bars .away_logo").append(
			$("<img class='logo' src='"+away_team["logo"]+"' />").attr("club_link", away_team["id"]).fadeIn(1000)
		);
	}
	
	if (nt_mode) {
		$(".top_team_bars .home_name").append(template_top_club_names(home_team["club_name"], home_team["club_nick"], home_team["country"])).fadeIn(1000);
		$(".top_team_bars .away_name").append(template_top_club_names(away_team["club_name"], away_team["club_nick"], away_team["country"])).fadeIn(1000);
	} else {
		$(".top_team_bars .home_name").append(template_top_club_names(home_team["club_name"], home_team["club_nick"], home_team["id"])).fadeIn(1000);
		$(".top_team_bars .away_name").append(template_top_club_names(away_team["club_name"], away_team["club_nick"], away_team["id"])).fadeIn(1000);
		activate_club_links($("[club_link]"));
	}
}




function make_tabs() {
	
	for (var i in tab_valid_ar) {
	
		function make_tab_header(className, header,index) {
			var div = $("<div>").addClass(className).append(
				$("<div>"+tab["header"]+"</div></div>").click(function() {
					change_tab(index);
				})
			);
			// Activate first tab
			if (index == 0) div.addClass("active_tab");
			
			return div;
		}
	
		var tab_name = tab_valid_ar[i];
		var tab = get_tab_data(tab_name);
		
		if (tab) {
			
			// Tab header
			$("#tabs .tabs_new").append(make_tab_header(tab_name, tab["header"], i));

			// Tab content
			var tab_content = $("<div>").attr("tab",tab_name).append($(tab["content"]));
			if (i>0) tab_content.hide();
			$("#tabs_content").append(tab_content);
			
		}
		
		// Make chat if there's a chat tab
		if (tab_name == "chat") {
			var chatroom_id = site_prefix+match_data["match_data"]["chatroom"] || chat_room_prefix+"default";
			create_chatroom(chatroom_id, "#chatroom", "#chattext", null, true, "#disable_chat_btn");
		}
		
	}
}


var main_max_height = "447px";

function pop_element_with_data() {
	
	make_tabs();
	
	element_stats = template_statistics();
	$("[tab='stats'] .half").hide().append(element_stats).fadeIn(500);

	element_score = template_score();
	
	element_home_player_list = template_field_list(lineup["home"]);
	$("[tab='field'] .quarter.home").html(element_home_player_list);
	
	element_away_player_list = template_field_list(lineup["away"]);
	$("[tab='field'] .quarter.away").html(element_away_player_list);
	
	element_field = template_field_div();
	$("[tab='field'] .half").html(element_field);
	
	element_venue = template_venue_div();
	$("[tab='stadium'] .half").first().html(element_venue);
	if (qm_mode) $("[tab='stadium'] .half").last().html(template_qm());

	//$("[tab='events'] .half").first().prepend(template_team_name_header());
	$("[tab='events'] .half").first().prepend(template_nameplate());
	
	// Fold out player if not prematch
	if (match_time_mode != "prematch") {
	
		$("#main").animate({height:main_max_height}, 1000, 'easeOutCubic', function() {	
			$(".mv_top .stats").hide().append(element_stats).fadeIn(500);
			
			// Add text
			//$(".actionclips").html("Please make sure Flash is installed.<br/>If you do not wish to see the game with animations, then you can disable them by clicking the <span class='red'>red X</span> to the right.");
			
			// Show disable flash btn
			$(".mv_top .flash_button_disable")
			.click(disable_animations)
			.tooltip("Disable animations")
			.fadeIn(500);
			
			var swf = "//static.trophymanager.com/flash/beta/"+site_prefix+"viewer.swf?0.1.15";
			//var swf = "/flash/beta/viewer.swf?"+new Date().getTime();
			
			var height = 200;
			//var height = 300;
			
			// Add flash
			$(".actionclips").flash({
				"allowScriptAccess":"always",
				"swf": swf,
				"width":300,
				"height":height,
				"id":"viewer",
				"flashvars": {loadingText:"<b> </b>", disableTxt:"<b>"+pagecontent[93]+"<br>"+pagecontent[96]+"</b>"}
			});
			
			
			// Make disable flash text
			var disable_text_div = $("<div class='disabled_text large bold faux_link'>").text(pagecontent[81]).click(function(e) {
				enable_flash();
			});
			
			// Hide if flash isn't disabled
			if (flash_status["enabled"]) disable_text_div.hide();
			
			// Append
			$(".actionclips").append(disable_text_div);
			
		});
	
	// Else hide overlays
	} else {
		$("#main .actiontext, #main .actionclips, #main .stats").hide();
	}
	
	$(".top_team_bars .score").hide().append(element_score).fadeIn(500);
	
	$(".clock").fadeOut(500, function() {
		if (match_time_mode == "prematch") {
			$(this).fadeIn(500);
			prematch_countdown();
		} else {
			$(this).text("00:00").fadeIn(500);
		}
	});
	
	
	var live_img = $("<img src='/pics/matchviewer/live.png'>");
	// Buttons and LIVE specific stuff
	if (match_time_mode == "live") {
		$(".buttons").append(template_live_img());
		
		// Override default MV settings
		start_with_flash_enabled = true;
		
		// Add previous action text to element
		var prev_min = get_previous_minute(skip_to_minute);
		
		if (prev_min) {
		
			for (var i in report[prev_min]) {
			
				if (settings["severity"] == 0 || (settings["severity"] == 1 && report[prev_min][i]["severity"] == 1)) {
					
					var entry = report[prev_min][i];
					
					// Prune action text holders
					var action_text_holders = $(".actiontext .scroller .entry");
					if (action_text_holders.size() > 6) action_text_holders.first().remove();
					
					// Make new action text holder				
					entry["time"] = prev_min;
					$(".actiontext .scroller").append(template_action_holder(entry, flash_status["enabled"]));
					$(".actiontext .scroller .entry, .actiontext .scroller p").show();
					
					var new_margin = 266-$(".scroller").outerHeight();
					$(".scroller").css({"margin-top": new_margin});
				}
			}
		}
		
	} else if (match_time_mode == "relive") {
		$(".buttons").append(
			template_control_button("pause playback","bump active").tooltip("Pause").click(toggle_playback),
			//template_control_button("play","bump active").tooltip("Play").click(match_play),
			template_control_button("all_events").tooltip("Show All Events").click(function() {set_severity(0);}),
			template_control_button("key_events","bump active").tooltip("Show Only Key").click(function() {set_severity(1);}),
			template_control_button("go_to_report").click(match_end)
		);
	}

	$(".buttons").fadeIn(500);
	
	if (!start_with_flash_enabled) {
		flash_status["enabled"] = false;
		// Mark flash as loaded
		flash_status["loaded_first_sequence"] = true;
	}
	
	
	if (!jQuery.browser.flash) {
		// No flash
		disable_animations();
		$(".actionclips").html("Match clips uses flash to play.<br><a href='http://www.adobe.com/go/getflashplayer' target='_blank' border='0'><img src='http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg' /></a>");
		
		// Mark flash as loaded
		flash_status["loaded_first_sequence"] = true;
		// Retry report, fix for content popping
		setTimeout(start_report, 1000);
	}
}


function disable_animations() {

	console.log("Disabling animations");
	createCookie("trophymanager[mv_flash_enabled]", "false", 365);
	flash_status["enabled"] = false;
	
	$("#viewer").remove();
	$(".actionclips").empty();
	$(".mv_top .flash_button_disable").remove();
	$(".download_icon").remove();
	
	// Remove tooltip after a short delay
	setTimeout(tooltip.hide, 1000);
	
	// Make sure report is started
	start_report();
		
	//$("#viewer")[0].gateway({"disable_clips":true});
	
	
}

// Enable flash
function enable_flash() {
	// Set flash as disabled
	flash_status["enabled"] = true;
	
	$(".actionclips .disabled_text").hide();
	
	createCookie("trophymanager[mv_flash_enabled]", "true", 365);

	// Register vars in player
	register_players(flash_player_info);
	register_extra_time(match_data["match_data"]["extra_time"]);
	
	// Show all texts
	$(".actiontext .scroller .entry, .actiontext .scroller p").show();
	
	prepare_next_minute();
}
	
function match_end() {
	
	// Avoid multiple match_ends
	if (end_of_game) return;
	match_last_min = 140;
	end_of_game = true;
	
	// Update stats
	update_stats();
	//update_elements_with_stats(true);
	element_score.update(true);

	// Change clock to whistle
	$(".clock").html($("<img src='/pics/matchviewer/whistle.png'/>").css("margin-top", "-5px").effect("pulsate"));
	
	// Remove data tables
	$(".stats").remove();
	$(".actiontext").remove();
	$(".actionclips").remove();
	
	$(".flash_button_disable").remove();
	
	$(".download_icon").hide();
	
	var chat_element = "";
	for (var i in chat_rooms) {
		if (!chat_rooms[i].disabled) {
			chat_element = $("[tab='chat']").detach();
			chat_element.find("#chattext").css("margin-left", "10px");
			chat_element.prepend(
				$("<div class='mega_headline tcenter report_section_header dark_bg'>").text("Chat")
			);
			break;
		}
	}
	
	
	$(".mv_bottom").empty();
	
	$(".mv_bottom").append(
		$("<div class='post_report'>").append(
			chat_element,
			$("<div class='mega_headline tcenter report_section_header dark_bg'>").text(pagecontent[83]),
			$("<div class='half'>").append(template_events()),
			$("<div class='half'>").append(template_statistics()),
			//$("<hr>"),
			$("<div class='mega_headline tcenter report_section_header dark_bg'>").text(pagecontent[84]),
			$("<div class='quarter'>").append(template_field_list(lineup["home"])),
			$("<div class='half'>").append(template_field_div()),
			$("<div class='quarter'>").append(template_field_list(lineup["away"])),
			//$("<hr>"),
			$("<div class='mega_headline tcenter report_section_header dark_bg'>").text(pagecontent[85]),
			$("<div class='half'>").append(template_report()),
			$("<div class='half'>").append(
				template_venue_div(),
				qm_mode ? template_qm().css("padding-top","30px") : ""
			)
		)

	);
	
	$("#main").animate({"height":"206px","margin-bottom":"-70px" }, 1000, 'easeOutCubic');
	
	// tutorial function
	if (typeof tutorial_match_end == "function") tutorial_match_end();
	
}



function get_text_from_chance(action) {
	function player_replace_function(str, p1) {
		return get_player_link_text(p1);
	}

	if (action) {
		try {
			action = action.replace(/\[br\]/gi, "<br/>");
			action = action.replace( /\[player=(\d+)\]/gi, player_replace_function);
			action = action.replace( /\[yellow\]/gi, "<img src='/pics/icons/yellow_card.gif'> ");
			action = action.replace( /\[red\]/gi, "<img src='/pics/icons/red_card.gif'> ");
			action = action.replace( /\[goal\]/gi, "<img src='/pics/icons/ball.gif'> ");
			action = action.replace( /\[sub\]/gi, "<img src='/pics/icons/subs.png'> ");
		} catch(e) {
			if(console) {
				//err
			}
		}
		var p = $("<p>").html(action);
		p.find("[player_id]").each(function() {
			var id = $(this).attr("player_id");
			$(this).tooltip(
				function() {
					make_player_link(id, miniGameId);
				}
			);
		});

		return p;
	}
	return null;
}

function get_display_time(time) {
	
	time = timeObj(time);
		
	var ret = new Object();
	
	// Stoppage Time
	if (time.m > 90 && time.m <= match_last_regular_min) {
		
		ret.formatted_s = "90:00 +"+(time.m-90)+":"+time.s_leading;
		ret.formatted_m = "90&acute; +"+(time.m-90)+"&acute;";

	// Extra Time
	} else if (time.m > 90) {
		
		ret.formatted_s = time.m_leading+":"+time.s_leading;
		ret.formatted_m = time.m+"&acute;";

	// Regular Time
	} else {

		ret.formatted_s = time.m_leading+":"+time.s_leading;
		ret.formatted_m = time.m+"&acute;";

	}

	if (ret.m < 0) ret.m = 0;
	
	return ret;
}

function add_to_report(report_event, time) {
	for (var i in report_event) {
		$("[tab='events'] .report_list").append(
			template_report_entry(report_event[i], time)
		);
	}
}


function add_to_events(report_event, time) {
	for (var i in report_event) {
		for (var m in report_event[i]["parameters"]) {
			var event = template_event_entry(report_event[i]["parameters"][m], time);
			if (event) $("[tab='events'] .event_list").append(event);
		}
	}
}


function add_to_stats(report_event) {
	
	var ret = [];
	
	function add_event(id, type, score) {
		if (typeof id == "string") id = [id];
		score = score || null;
		event_list_ar.push({
			"id":id,
			"type":type,
			"minute":get_display_time(i*60).formatted_m,
			"score":score
		});
	}
	for (var i in report_event) {
		
		for (var m in report_event[i]["parameters"]) {
		
			var penalty;
			var row = report_event[i]["parameters"][m];
			
			// Team Stats
			// - Shot
			if (row["shot"]) {
				
				side = get_team_side_from_team_id(row["shot"]["team"]);
				
				if (side !== false) {
					data_match_stats["shots"][side]++;
					// Shot On Target
					if (row["shot"]["target"] == "on") {
						data_match_stats["shots_on_target"][side]++;
					}
				}
				
			}
			
			// - Setpieces
			if (row["set_piece"]) {
			
				side = get_team_side_from_player_id(row["set_piece"]);
				if (side !== false) {
					data_match_stats["set_pieces"][side]++;
				}
			}
			
			// - Penalty
			if (row["penalty"]) {
				
				//penalty = row["penalty"];
				side = get_team_side_from_player_id(row["penalty"]);
				if (side !== false) {
					data_match_stats["penalty"][side]++;
				}
			}
			
			// - Goal
			if (row["goal"]) {
				
				var player = get_player_from_id(row["goal"]["player"]);
				if (player && penalty) {
					add_event(row["goal"]["player"], "penalty_goal", (row["goal"]["score"][0]+"-"+row["goal"]["score"][1]));
				} else {
					add_event(row["goal"]["player"], "goal", (row["goal"]["score"][0]+"-"+row["goal"]["score"][1]));
				}
				
				if (player) player["match_stats"].push("goal");

				side = get_team_side_from_player_id(row["goal"]["player"]);
				data_match_stats["score"] = row["goal"]["score"];
				
			}
			// - Yellow
			if (row["yellow"]) {
				side = get_team_side_from_player_id(row["yellow"]);
				if (side !== false) {
					data_match_stats["yellow"][side]++;
				}
				var player = get_player_from_id(row["yellow"]);
				if (player) { player["match_stats"].push("yellow"); }
			}
			// - Red
			if (row["red"]) {
				side = get_team_side_from_player_id(row["red"]);
				if (side !== false) {
					data_match_stats["red"][side]++;
				}
				
				var player = get_player_from_id(row["red"]);
				if (player) player["match_stats"].push("red");
				if (player) player["position"] = "sub";
				
			}
			
			// - Yellow Red
			if (row["yellow_red"]) {
				side = get_team_side_from_player_id(row["yellow_red"]);
				if (side !== false) {
					data_match_stats["red"][side]++;
				}
				
				var player = get_player_from_id(row["yellow_red"]);
				if (player) player["match_stats"].push("yellow_red");
				if (player) player["position"] = "sub";
				
			}
			
			// Injury
			if (row["injury"]) {
				// no stats
				add_event(row["injury"], "injury");
				var player = get_player_from_id(row["injury"]);
				if (player) player["match_stats"].push("injury");
			}
			// Sub
			if (row["sub"]) {
				// no stats
				add_event([row["sub"]["player_out"], row["sub"]["player_in"]], "sub");
				var player_out = get_player_from_id(row["sub"]["player_out"]);
				var player_in = get_player_from_id(row["sub"]["player_in"]);

				if (player_in) player_in["match_stats"].push("in");
				if (player_in) player_in["position"] = (row["sub"]["player_position"] != null) ? row["sub"]["player_position"] : player_out["position"];
				if (player_out) player_out["match_stats"].push("out");
				if (player_out) player_out["position"] = "sub";
			}

			// Player Change
			if (row["player_change"]) {

				var player = get_player_from_id(row["player_change"]["player"]);
				//var team = lineup[get_team_side_from_player_id(row["player_change"]["player"])];
				var teamSide = get_team_side_from_player_id(row["player_change"]["player"]);
				var team = lineup[(teamSide==1 ?'away' :'home')];
				var new_position = row["player_change"]["position"];
				var colliding_player = false;

				// Look over team for colliding positions
				for (var g in team) {
					if (team[g]["position"] == new_position) {
						// Colliding
						colliding_player = team[g];
					}
				}

				// Quick fix
				// If player collides, move him
				if (colliding_player) {
					var new_side = get_player_side(new_position);
					var new_line = get_player_line(new_position);
					if ((new_side+"").indexOf("c") !== -1) {
						var available_pos = {};//(new_line+'c'): true, (new_line+'cl'):true, (new_line+'cr': true};
						available_pos[new_line+'cl'] = true;
						available_pos[new_line+'cr'] = true;
						//available_pos[new_line+'c'] = true;
						available_pos[new_line+'c'] = new_line == 'd' || new_line == 'm' || new_line == 'f';
						available_pos[new_position] = false;
						for (var g in team) {
							var pp = team[g];
							if(pp.player_id != row.player_change.player
								&& available_pos[pp.position]) {
								available_pos[pp.position] = false;
							}
						}
						for (var gg in available_pos) {
							if (available_pos[gg]) {
								new_position = gg;
								break;
							}
						}
						console.log('colliding new x', new_position, available_pos);
					}
					/*
					if (new_position == "fc") {
						//colliding_player["position"] = "fcr";
						player["position"] = "fcl";
					} else if (new_position == "omc") {
						//colliding_player["position"] = "omcr";
						player["position"] = "omcl";
					} else if (new_position == "mc") {
						//colliding_player["position"] = "mcr";
						player["position"] = "mcl";
					} else if (new_position == "dmc") {
						//colliding_player["position"] = "dmcr";
						player["position"] = "dmcl";
					} else if (new_position == "dc") {
						//colliding_player["position"] = "dcr";
						player["position"] = "dcl";
					}
					*/

				// Else just place the player on the new position
				} else {
				}
				player["position"] = new_position;
			}
			// Mentality/Style change
			if (row["mentality_change"]) {
				var team_side = get_team_side_from_team_id(row["mentality_change"]["team"]);
				if (row["mentality_change"]["mentality"]) {
					match_info["mentality"][team_side] = row["mentality_change"]["mentality"];
				} else if (row["mentality_change"]["style"]) {
					match_info["attacking_style"][team_side] = parseInt(row["mentality_change"]["style"]);
				}
			}
		}
	}
}






function set_severity(severity) {
	if (severity === 1) {
		$(".key_events").parent(".control_button").addClass("active");
		$(".all_events").parent(".control_button").removeClass("active");
	} else if (severity === 0) {
		$(".key_events").parent(".control_button").removeClass("active");
		$(".all_events").parent(".control_button").addClass("active");
	}
	settings["severity"] = severity;
}



// Tab switch hotkey
$("body").live("keydown", function (e) {
	// Tab-key
	if (e.shiftKey && e.keyCode == 9) { 
		change_tab("-");
		return false;
	} else if (e.keyCode == 9){
		change_tab("+");
		return false;
	}
});

function change_tab(tab) {
	
	if (!match_data && tab!=0) return false;
	
	// Bump
	if (tab == "+") tab = (tab_active+1 < tab_valid_ar.length) ? tab_active+1 : 0;
	else if (tab == "-") tab = (tab_active == 0) ? tab_valid_ar.length-1 : tab_active-1;
	
	// Convert to int
	tab=parseInt(tab);
	
	if (tab_active != tab && tab_valid_ar[tab] != undefined) {
	
		if (tab_valid_ar[tab] == "league") load_live_data();
		if (tab_valid_ar[tab] == "head_to_head") load_head_to_head();
		
		tab_active = tab;
		var tab_name = tab_valid_ar[tab];
		$("[tab]").hide();
		$("[tab="+tab_name+"]").show();
		$("#tabs > div > div").removeClass("active_tab");
		$("#tabs ."+tab_name).addClass("active_tab");
	}
}


function test_flash_played_minute(i) {
	if (!flash_status["enabled"]) return true;
	return ($.inArray(i, flash_played_minutes_ar) >= 0);
}
function test_flash_finished_loaded(i) {
	if (!flash_status["enabled"]) return true;
	return ($.inArray(i, flash_finished_loaded_minutes_ar) >= 0);
}

function get_next_minute_with_severity(current_minute) {
	
	for (var i = current_minute+1; i<140; i++) {
		if (report[i] != undefined) {
			if (settings["severity"] == 1) {
				for (var j in report[i]) {
					if (report[i][j]["severity"]) return i;
				}
			} else {
				return i;
			}
		}
	}
	return false;
}
function get_next_minute(current_minute) {
	// Add halftime
	for (var i = current_minute+1; i<140; i++) {
		if (report[i] != undefined) return i;
	}
	return false;
}
function get_previous_minute(current_minute) {
	for (var i = current_minute-1; i>=0; i--) {
		if (report[i] != undefined) return i;
	}
	return false;
}
function get_closest_minute(current_minute) {

	for (var i = current_minute; i<140; i++) {
		if (report[i] != undefined) return i;
	}
	return false;
}

function update_elements_with_stats(show_animation) {
	//console.log("updating all elements");
	show_animation = (show_animation==true);
	element_stats.update(show_animation);
	element_score.update(show_animation);
	element_field.update(show_animation);
}



function start_report() {
	
	// Report already started?
	if (flash_status["report_started"]) return false;
	
	// Everything loaded
	if (
		(
			(flash_status["loaded_main"] == true && flash_status["loaded_refblow"] == true)
			|| !flash_status["enabled"]
		)
		&& flash_status["loaded_first_sequence"]
	) {
	
		console.log("Running Match");
		
		flash_status["report_started"]=true;
		run_match();
		
	// Load flash
	} else if (
		(flash_status["loaded_main"] == true && flash_status["loaded_refblow"] == true)
		|| !flash_status["enabled"]
	) {
	
		console.log("Starting report");
	
		register_players(flash_player_info);
		register_extra_time(match_data["match_data"]["extra_time"]);

		// Skip minute?
		if (match_time_mode == "relive" && hash.get("time")) {
			skip_to_minute = parseInt(hash.get("time"));
		}
		
		// Set times
		match_last_min = skip_to_minute-1;
		match_seconds = skip_to_minute*60;
		
		// Update stats
		update_stats();
		update_elements_with_stats(true);
		
		prepare_next_minute();
		
	}
}
	
/*
// Will check if next minute is prepared, incase of severity switch between clips
function check_next_minute() {

	var next_action_minute = get_next_minute_with_severity(match_last_min);
	
	// Next minute has not been prepared
	if ($.inArray(next_action_minute, flash_start_loaded_minutes_ar)<0) {
		prepare_next_minute();
	}
	
}
*/

var match_prepared_minutes = [];
function test_prepared_minute(i) {
	return ($.inArray(i, match_prepared_minutes) >= 0);
}

function prepare_next_minute() {
	
	match_next_minute = get_next_minute_with_severity(match_last_min);
	
	if (match_next_minute !== false && !test_prepared_minute(match_next_minute)) {
		
		console.log("Prepareing next minute - "+match_next_minute);
		
		// Add minute as has been prepared
		match_prepared_minutes.push(match_next_minute);
		
		// Merge all videos for the loader and prepare text boxes
		var video_list = [];
		
		for (var i in report[match_next_minute]) {
		
			if (settings["severity"] == 0 || (settings["severity"] == 1 && report[match_next_minute][i]["severity"] == 1)) {
				
				var entry = report[match_next_minute][i];
				
				// Prune action text holders
				var action_text_holders = $(".actiontext .scroller .entry");
				if (action_text_holders.size() > 6) action_text_holders.first().remove();
				var new_margin = 266-$(".scroller").outerHeight();
				$(".scroller").css({"margin-top": new_margin});
				
				// Add time to entry
				entry["time"] = match_next_minute;
				
				// Make new action text holder				
				$(".actiontext .scroller").append(template_action_holder(entry, flash_status["enabled"]));
				
				// Add videos to video list
				if (entry["chance"]["video"]) video_list = video_list.concat(entry["chance"]["video"]);
			
			}
		}
		
		if (video_list.length>0 && flash_status["enabled"]) {
			
			flash_start_loaded_minutes_ar.push(match_next_minute);
			
			// Cashe fix, treats duplicates as unique clips, otherwise animation complete will not fire.
			for (var i in video_list) {
				for (var j in video_list) {
					if (i!=j) {
						if (video_list[i]["video"]==video_list[j]["video"]) {
							video_list[i]["video"] = video_list[i]["video"]+"?"+i;
						}
					}
				}
			}
			
			load_clips(video_list, match_next_minute);
			
		} else {
		
			flash_finished_loaded_minutes_ar.push(match_next_minute);
			flash_played_minutes_ar.push(match_next_minute);
			
			// Make sure report is running
			if (!flash_status["report_started"]) start_report();
			
		}
	}
}

function add_to_player_list(event) {
	for (var i in event) {
		if (event[i]["parameters"] != undefined) {
			for (var m in event[i]["parameters"]) {
				for (var j in event[i]["parameters"][m]) {
					if ($.inArray(j, ["goal","yellow","red","yellow_red","injury","out","in","mom"]) >= 0) {
						element_home_player_list.update(lineup["home"]);
						element_away_player_list.update(lineup["away"]);
						break;
					}
				}
			}
		}
	}
}
function add_to_field(event) {
	for (var i in event) {
		if (event[i]["parameters"] != undefined) {
			for (var m in event[i]["parameters"]) {
				for (var j in event[i]["parameters"][m]) {
					if ($.inArray(j, ["sub"]) >= 0) {
						element_field.update();
						break;
					}
				}
			}
		}
	}
}

function update_live_elements(force_this_minute) {
	
	function check_time(i) {
		if (force_this_minute) return i<=match_last_min;
		return i<match_last_min;
	}

	if (live) {
		
		if (live["last_update"] <= match_last_min) {
			
			var i=live["last_update"];
			while (check_time(i)) {
				if (live["goals"][i] != undefined) {
					add_live_goals(live["goals"][i], i);
				}
				
				
				
				i++;
			}
			
			live["last_update"] = i;
			
		}
	
		element_live_score.update();
		element_live_standing.update();
	}
		
}

function update_stats(pre_mode) {

	// pre mode will ignore current minute, used for relive to update "missing stats" that are not seen due to severity
	var goto_minute = (pre_mode) ? match_last_min-1 : match_last_min;
	console.log("Updating stats: "+goto_minute);
	while (match_last_stats_min < goto_minute) {
	
		match_last_stats_min++;
		
		if (report[match_last_stats_min] != undefined) {
		
			// Update scoreboard and stats
			add_to_stats(report[match_last_stats_min]);
			
			// Add event to report and events
			add_to_report(report[match_last_stats_min], match_last_stats_min);
			add_to_events(report[match_last_stats_min], match_last_stats_min);
			
			// Update player list and field in the field tab
			add_to_player_list(report[match_last_stats_min]);
			add_to_field(report[match_last_stats_min]);
			
		}
	}
}

var countdown;
function prematch_countdown() {
	
	if (countdown <= 0) {
		$(".clock").html("...");
		location.reload();
	}
	$(".clock").html("Kick-off in: "+time_left_abs_ignore_secs(countdown--));
	setTimeout(prematch_countdown,1000);
}

function run_match() {
	
	var time = timeObj(match_seconds);
	
	// Stop if end of game
	if (end_of_game) return;
	// End at end of game
	if (time.m >= end_game && !flash_playing_clip && !$(".actiontext .scroller p:hidden").length > 0) {
		match_end();
		return;
	}
		
	// Paused? Wait a sec and check for unpaused then
	if (flash_status["playback_mode"] == "pause") {
		setTimeout(run_match,1000);
		return false;
	}
	

	// Update clock
	//$(".clock").text(time.m_leading+":"+time.s_leading);
	$(".clock").text(get_display_time(match_seconds).formatted_s);
		
	// Start half time
	if (time.m == 45 && match_half_time === false && match_time_mode == "live") {
	
		match_half_time = 0;
		play_refblow();
		setTimeout(run_match,1000);
		return false;
		
	// Continue half time
	} else if (time.m == 45 && match_half_time <= 900 && match_time_mode == "live") {
	
		var half_time = timeObj(900-match_half_time);
		$(".ht_clock").show().text(half_time.m_leading+":"+half_time.s_leading);
		
		match_half_time++;
		
		// Hide clock
		if (match_half_time >= 900) $(".ht_clock").hide();
		
		setTimeout(run_match,1000);
		return false;
		
	} else if (time.m >= 45 && match_half_time===false && match_time_mode == "relive") {
		match_half_time = true;
		element_venue.update();
	}
	
	
	// No flash
	if (!flash_status["enabled"]) {
		if ($(".scroller p:hidden").size() > 0 && time.m >= match_next_minute) {
			show_next_action_text_entry();
		} else {
			finish_playing(0);
		}
	}
	
	
	
	
	// Match still going on
	if (match_last_min != Math.floor(match_seconds/60)) {
	
		// New minute called
		match_last_min = Math.floor(match_seconds/60);
		
		console.log("New minute called: "+match_last_min);
		
		update_stats(true);
		update_elements_with_stats(false);
		update_live_elements();
		
		if (report[match_last_min]) {
			play_clips(match_last_min);	
		}
		
	}
	
	
	
	// *** Bump time ***
	// Next minute loaded and current minute playback done speed up clock
	if (match_time_mode == "relive" && test_flash_finished_loaded(match_next_minute) && test_flash_played_minute(match_last_min)) {
		if (match_seconds < match_next_minute*60) {
			match_seconds = match_next_minute*60;
		} else {
			match_seconds++;
		}
		
	// Allow clock to go
	} else if ($.inArray(match_next_minute, flash_finished_loaded_minutes_ar) >= 0) {
		match_seconds++;
		
	// Disallow clock to pass match_next_minute until the clips are loaded for that minute
	} else if (Math.floor((match_seconds+1)/60) < match_next_minute) {
		match_seconds++;
	}
	
	setTimeout(run_match,1000);
	
}
function finish_playing(id) {

	// Mark minute as has been played
	flash_played_minutes_ar.push(id);
	flash_playing_clip = false;
	
	//console.log("finished playing: "+id);
	update_stats();
	update_elements_with_stats();
	
	//check_next_minute();
	prepare_next_minute();
	
}

function gateway(vars) {

	// Flash is ready and loaded
	if (vars["flash_ready"]) {
		// Start preloading
		flash_status["loaded_main"] = true;
		
		if (match_time_mode == "live") {
			preload_refblow();
		} else {
			flash_status["loaded_refblow"] = true;
		}
		
		start_report();
	}
	
	// Refblow has been loaded
	if (vars["preload_refblow_done"]) {
		// Start preloading
		flash_status["loaded_refblow"] = true;
		start_report();
	}
	
	
	
	
	// Finished loading a sequence
	if (vars["finished_loading"]) {
	
		$(".download_icon").hide();
		
		
		flash_status["loaded_first_sequence"] = true;
		// Mark minute as has been loaded
		flash_finished_loaded_minutes_ar.push(vars["finished_loading"]["id"]);
		
		// Start match
		start_report();
		
	}
	
	if (vars["finished_playing"]) {
		
		finish_playing(vars["finished_playing"]["id"]);
		update_live_elements(true);
		
	}
	
	if (vars["progress"]) {
		$("#error_out").append(vars["progress"]["status"]);
	}
	
	if (vars["finished_clip"]) {
		//console.log("Finished: "+vars["finished_clip"]["count"]);
		show_next_action_text_entry();
	}
	
	if (vars["starting_clip"]) {
	
		//vars["starting_clip"]["count"];
		//console.log("Starting: "+vars["starting_clip"]["clip"]);
		flash_playing_clip = true;
		
	}
}

function show_next_action_text_entry(all) {
	if (all) {
		$(".scroller :hidden").show();
	} else {
		var p = $(".scroller p:hidden").first().fadeIn();
		p.parent(".entry").show();
	}
	
	var new_margin = 266-$(".scroller").outerHeight();
	$(".scroller").css({"margin-top": new_margin});
}


function template_glare(i) {
	var className = (Math.random()<0.5) ? "glare" : "glare small";
	var div = $("<div>").addClass(className).css({
		"left":glare_spawn_coordinates[i][0],
		"top":glare_spawn_coordinates[i][1]
	});
	return div.hide().delay(i*200).effect("pulsate",{ times:3 }, 200, function() {$(this).remove();});
}

var glare_spawn_coordinates = [
	// Left
	[180,57],
	[210,52],
	[240,47],
	[270,41],
	[300,36],
	// Right
	[670,36],
	[700,41],
	[730,47],
	[760,52],
	[790,57]
];

function animate_goal_flash() {
	glare_spawn_coordinates.sort(function() { return 0.5 - Math.random(); });
	for (var i in glare_spawn_coordinates) {
		$("#main").append(template_glare(i));
	}
	$(".mv_top .away_color").effect("pulsate",{ times:9 }, 200);
	
	
}


// Flash: Toggle Playback
function toggle_playback() {
	(flash_status["playback_mode"] == "play") ? match_pause() : match_play();
}
// Flash: Play
function match_play() {
	$("div#main div.buttons div.control_button div.playback").removeClass("play").addClass("pause");
	flash_status["playback_mode"] = "play";
	var passalong = {"playback_mode":"play"};
	if ($("#viewer")[0]) $("#viewer")[0].gateway(passalong);
}
// Flash: Pause
function match_pause() {
	$("div#main div.buttons div.control_button div.playback").removeClass("pause").addClass("play");
	flash_status["playback_mode"] = "pause";
	var passalong = {"playback_mode":"pause"};
	if ($("#viewer")[0]) $("#viewer")[0].gateway(passalong);
}
// Flash: register players
function register_players(data) {
	var passalong = {"register_players":flash_player_info};
	if ($("#viewer")[0]) $("#viewer")[0].gateway(passalong);
}
// Flash: register added time
function register_extra_time(extra_time) {
	var passalong = {"extra_time":extra_time};
	if ($("#viewer")[0]) $("#viewer")[0].gateway(passalong);
}
// Flash: preload refblow
function preload_refblow() {
	var passalong = {"preload_refblow":true};
	if ($("#viewer")[0]) $("#viewer")[0].gateway(passalong);
}
// Flash: play ref blow
function play_refblow() {
	var passalong = {"play_refblow":true};
	if ($("#viewer")[0]) $("#viewer")[0].gateway(passalong);
}

// Flash: load clips
function load_clips(videos,minute) {
	/*
	console.log("Video list");
	console.log(videos);
	*/
	$(".download_icon").show();
	
	var passalong = {
		"load_clips":{
			"queue":videos,
			"id":minute
		}
	};
	$("#viewer")[0].gateway(passalong);
}

// Flash: play clips
function play_clips(minute) {

	var passalong = {
		"play_clips":{
			"id":minute
		}
	};
	if ($("#viewer")[0]) $("#viewer")[0].gateway(passalong);
}

// Trace for flash
function output(output) {
	//console.log("Flash out: "+output);
}




function go_mv() {
	/*
	$("#tabs .field").click(function() {change_tab(0)});
	$("#tabs .league").click(function() {change_tab(1)});
	$("#tabs .events").click(function() {change_tab(2)});
	$("#tabs .stadium").click(function() {change_tab(3)});
	//$("#tabs .head_to_head").click(function() {change_tab(4)});
	$("#tabs .chat").click(function() {change_tab(4)});
	change_tab(0);
	*/
	
	$(".download_icon").hide();
	$("#error_out").hide();
	
	// Load match after short delay
	setTimeout(load_match, 500);
	
}

$(go_mv);
